<?php
/**
 * Created by PhpStorm.
 * User: Yangjinlei
 * Date: 2018/6/27
 * Time: 14:57
 */

namespace App\Http\Controllers\V1;


use App\Exceptions\ServerException;
use App\Http\Controllers\ApiBaseController;
use App\Jobs\SendMails;
use App\Repositories\UserRepository;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\JWTAuth;

/**
 * @property UserRepository repository
 * @property JWTAuth auth
 */
class AuthController extends ApiBaseController
{
    public function __construct(UserRepository $repository,JWTAuth $auth)
    {
        $this->repository=$repository;
        $this->auth = $auth;
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws ServerException
     * @throws \Exception
     */
    public function login(Request $request)
    {
        if (cache('api_token')!==null){
            return $this->success(['token'=>cache('api_token')]);
        }
        $credentials = $request->only('name','password');
        try{
            if (!$token = auth('api')->attempt($credentials)){
                return $this->failed(400,"登录失败");
            }
        }catch (JWTException $exception){
            throw new ServerException("JWTException");
        }
        cache(['api_token'=>$token],Carbon::now()->addHour());
        return $this->success(compact('token'));
    }

    public function logout(){
        $user = $this->repository->find(9);
    }

    public function register(Request $request){
        $credentials = $request->only(['name','password','eamils']);
        $credentials['password'] = bcrypt($credentials['password']);
        $user = $this->repository->create($credentials);
        //发送注册队列任务
        dispatch((new SendMails($user))->onQueue('emails'));
        return $this->success(['message'=>'恭喜您注册成功,请您前往邮箱激活您的账号']);
    }

    public function redirectToProvider(Request $request,$service){
        return Socialite::driver($service)->redirect();
    }

    public function handleProviderCallback(Request $request,$service)
    {
        $user = Socialite::driver($service)->user();
        dd($user);
    }

    public function weixin(){
        return view('oauth.weixin');
    }

    public function refresh(){

    }
}